/*
 * ===================================================================
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 * ===================================================================
 */

package com.brsanthu.jdtools.jarver;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;
import java.util.jar.Attributes;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;
import java.util.jar.Manifest;

public class JarVer {

    private static final String VERSION = "1.0.0";
    private static final byte[] BUFFER = new byte[100 * 1024];

    private Set set = new TreeSet();

    public static void main(String[] args) {
        new JarVer().execute(args);
    }

    public void execute(String[] args) {
        if (args.length == 0 || args[0].trim().length() == 0) {
            printUsage();
            return;
        }

        int fileNameIndex = 0;
        String fileName = null;
        boolean recursive = false;

        if (args[0].equals("-r")) {
            recursive = true;
            if (args.length < 2) {
                printUsage();
                return;
            }
            fileNameIndex = 1;
        }

        for (int i = fileNameIndex; i < args.length; i++) {
            fileName = args[i];
            try {
                File f = new File(fileName);
                JarInputStream jarStream = new JarInputStream(new FileInputStream(f));

                if (recursive) {
                    printVersions("", f.getName(), jarStream);
                    Iterator itr = set.iterator();
                    while (itr.hasNext()) {
                        System.out.println(itr.next());
                    }
                } else {
                    printVersion(f.getName(), jarStream.getManifest());
                }

            } catch (IOException e) {
                System.out.println(fileName + ": " + "Couldn't read the file");
            }
        }
    }

    private void printVersions(String parent, String name, JarInputStream jarStream)
        throws IOException {
        printVersion(parent + name, jarStream.getManifest());

        JarEntry entry = jarStream.getNextJarEntry();

        while (entry != null) {
            String entryName = entry.getName();
            if (entryName.endsWith(".war") || entryName.endsWith(".ear")
                || entryName.endsWith(".jar")) {
                printVersions(parent + name + "!", entryName, new JarInputStream(
                                new ByteArrayInputStream(readJarEntry(jarStream))));
            }

            entry = jarStream.getNextJarEntry();
        }
    }

    private String getVersion(String entryName, Manifest manifest) {
        if (manifest == null) {
            return entryName + ": Manifest file is missing.";
        }

        Attributes attributes = manifest.getMainAttributes();
        String specVer = attributes.getValue("Specification-Version");
        if (specVer == null) {
            specVer = "<missing>";
        }

        String implVer = attributes.getValue("Implementation-Version");
        if (implVer == null) {
            implVer = "<missing>";
        }

        return (entryName + ": " + specVer + " (" + implVer + ")");
    }

    private byte[] readJarEntry(JarInputStream jarStream) throws IOException {
        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        while (jarStream.available() != 0) {
            int readBytes = jarStream.read(BUFFER);
            bo.write(BUFFER, 0, readBytes == -1 ? 0 : readBytes);
        }

        return bo.toByteArray();
    }

    private void printVersion(String entryName, Manifest manifest) {
        System.out.println(getVersion(entryName, manifest));
    }

    private void printUsage() {
        System.out.println("JarVer Version " + VERSION);
        System.out.println("");
        System.out.println("Usage: jarver [options] <jar|war|ear file>");
        System.out.println("");
        System.out.println("Options are:");
        System.out.println("    -r recursively prints the versions of all supported files inside the specified file");
        System.out.println("");
        System.out.println("The output format is:");
        System.out.println("<FileName!EntryName>: <Specification-Version> (<Implementation-Version>)");
        System.out.println("If a verison is missing in the minifest file, it prints <missing>");
    }
}
